/*
 * Created on Wed Oct 04 2017
 * @flow
 * Copyright (c) 2017 jianglinjie
 */
'use strict';

import AuthService from '../../src/services/auth';
import * as ServiceConst from './ServiceConst';
import { ErrorCode } from '../../src/constants';
import { GlobalDefines } from '../../src/constants';

import { 
  loginWithAccount,
  loginWithPhone
} from './ServiceHelper';

test('Account(username)_ENCRYPTPWD_LOGIN', async () => {
  let result = await loginWithAccount(ServiceConst.TEST_USER_NAME, ServiceConst.TEST_USER_NAME_PWD);

  expect(result.token).toBeTruthy();
  expect(result.userInfo).toBeTruthy();  
  expect(result.userInfo.uid).toBeTruthy();
  expect(result.userInfo.userName).toMatch(ServiceConst.TEST_USER_NAME);      
  let tokenPayload = await AuthService.parseToken(result.token);
  expect(tokenPayload.uid).toMatch(result.userInfo.uid);
});

test('Account(phone)_ENCRYPTPWD_LOGIN', async () => {
  let result = await loginWithAccount(ServiceConst.TEST_PHONE, ServiceConst.TEST_PHONE_PWD);
  
  expect(result.token).toBeTruthy();
  expect(result.userInfo).toBeTruthy();  
  expect(result.userInfo.uid).toBeTruthy();
  expect(result.userInfo.phone).toMatch(ServiceConst.TEST_PHONE);      
  let tokenPayload = await AuthService.parseToken(result.token);
  expect(tokenPayload.uid).toMatch(result.userInfo.uid);
});

test('PHONE_CAPTCHA_LOGIN', async () => {
  let result = await loginWithPhone(ServiceConst.TEST_PHONE);
  
  expect(result.token).toBeTruthy();
  expect(result.userInfo).toBeTruthy();  
  expect(result.userInfo.uid).toBeTruthy();
  expect(result.userInfo.phone).toMatch(ServiceConst.TEST_PHONE);      
  let tokenPayload = await AuthService.parseToken(result.token);
  expect(tokenPayload.uid).toMatch(result.userInfo.uid);
});

test('LOGOUT_OUT', async () => {
  let result = await loginWithAccount(ServiceConst.TEST_PHONE, ServiceConst.TEST_PHONE_PWD);
  await AuthService.logout({
    token: result.token
  });
  try {
    await AuthService.parseToken(result.token);
  } catch (err) {
    expect(err[GlobalDefines.CUSTOM_ERROR_CODE_KEY]).toMatch(ErrorCode.TOKEN_INVALID);
  }
});